import logging

from sqlalchemy.orm import Session

from app.core.config import settings
from app.core.security import get_password_hash
from app.models.user import User

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def init_db(db: Session) -> None:
    """
    初始化数据库
    """
    # 创建超级用户（如果不存在）
    user = db.query(User).filter(User.email == settings.FIRST_SUPERUSER).first()
    if not user:
        logger.info("创建初始超级用户")
        user_obj = User(
            email=settings.FIRST_SUPERUSER,
            hashed_password=get_password_hash(settings.FIRST_SUPERUSER_PASSWORD),
            full_name="Initial Super User",
            is_superuser=True,
        )
        db.add(user_obj)
        db.commit()
        logger.info("超级用户创建成功")
    else:
        logger.info("超级用户已存在，跳过创建") 